# Create your models here.
# parts/models.py
from django.db import models
from django.utils import timezone

class Parts(models.Model):
    id = models.AutoField(primary_key=True)
    sn = models.CharField(max_length=32)
    create_time = models.DateTimeField(default=timezone.now)
    status = models.SmallIntegerField(choices=[
        (0, 'Pending'),
        (1, 'In Progress'),
        (2, 'Completed')
    ])

    class Meta:
        managed = False  # 禁用Django的自动建表
        db_table = 'parts'
        unique_together = (('id', 'create_time'),)

    @classmethod
    def create_partition(cls, year: int, month: int):
        """创建分区表的原生SQL操作"""
        from django.db import connection
        table_name = f'parts_{year}_{month:02d}'
        
        with connection.cursor() as cursor:
            cursor.execute(f"""
                CREATE TABLE {table_name} PARTITION OF parts
                FOR VALUES FROM ('{year}-{month:02d}-01') 
                TO ('{year}-{month+1:02d}-01');
            """)